package com.sunjs.pay.controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.sunjs.model.Payment;
import com.sunjs.model.back.ReturnDto;
import com.sunjs.pay.service.PaymentLogService;
import com.sunjs.pay.service.PaymentService;
import com.sunjs.pay.util.PayUtil;

/**
 * 支付
 * @author wang
 *
 */
@RestController
@RequestMapping("/payment")
public class PaymentController {
	
	private static Logger logger = LoggerFactory.getLogger(PaymentController.class);
    
    @Autowired
    private PaymentService paymentService;
    
    @Autowired
    private PaymentLogService paymentLogService;

    /**
	 * 统一下单入口
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
    @RequestMapping(value="toPay", method=RequestMethod.POST, produces ={"application/json;charset=UTF-8"})
	public ReturnDto toPay(HttpServletRequest request,@RequestBody Payment pay) throws Exception {
		if (StringUtils.isEmpty(pay.getOrderNo())) {
			return new ReturnDto("参数错误：id不能为空！");
		}
		// 获取订单
		Payment payment =paymentService.getPayment(pay);
	   			
	   	if(payment == null){
	   		paymentLogService.insertPaymentLogByPayment(payment,"订单不存在！");
	   		return new ReturnDto("订单不存在！");
	   	}else if(StringUtils.isEmpty(payment.getPayAmount()) || payment.getPayAmount() <= 0){
	   		paymentLogService.insertPaymentLogByPayment(payment,"订单有误，请确认！");
	   		return new ReturnDto("订单有误，请确认！");
	   	}else if(payment.getStatus() != 1){
	   		String msg = payment.getStatus() >1 ?"此订单已支付！":"订单未提交，请确认！";
	   		paymentLogService.insertPaymentLogByPayment(payment,msg);
	   		return new ReturnDto(msg);
	   	}else{
	   		logger.info("【小程序支付服务】请求订单编号:["+payment.getOrderNo()+"]");
		   	Map<String, Object> resMap = paymentService.xcxPayment(payment.getOrderName(),payment.getOrderNo(),payment.getPayAmount(),payment.getOpenId());
		   	if("SUCCESS".equals(resMap.get("returnCode")) && "OK".equals(resMap.get("returnMsg"))){
		   		//统一下单成功
		   		resMap.remove("returnCode");
		   		resMap.remove("returnMsg");
		   		logger.info("【小程序支付服务】支付下单成功！");
		   		paymentLogService.insertPaymentLogByPayment(payment,"小程序支付服务 支付下单成功！");
		   		return new ReturnDto(resMap);
		   	}else{
		   		logger.info("【小程序支付服务】支付下单失败！原因:"+resMap.get("returnMsg"));
		   		paymentLogService.insertPaymentLogByPayment(payment,"【小程序支付服务】支付下单失败！原因:"+resMap.get("returnMsg").toString());
		   		return new ReturnDto(resMap.get("returnMsg").toString());
		   }
	   	}
	   	
	}
	
	/**
	 * 回调Api
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
    @RequestMapping(value="xcxNotify")
	public void xcxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception {
        
 		InputStream inputStream =  request.getInputStream();
 		//获取请求输入流
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,len);
        }
        outputStream.close();
        inputStream.close();
        Map<String,Object> map = PayUtil.getMapFromXML(new String(outputStream.toByteArray(),"utf-8"));
        logger.info("【小程序支付回调】 回调数据： \n"+map);
        String resXml = "";
        String returnCode = (String) map.get("return_code");
        Payment payment = new Payment();
        payment.setOrderNo((String) map.get("out_trade_no"));
        paymentLogService.insertPaymentLogByPayment(payment,"【小程序支付回调】 回调数据： \n"+map.toString());
        if ("SUCCESS".equalsIgnoreCase(returnCode)) {
            String returnmsg = (String) map.get("result_code");
            if("SUCCESS".equals(returnmsg)){
            	//更新数据
            	int result = paymentService.xcxNotify(map);
            	if(result > 0){
	            	//支付成功
	                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
	                        + "<return_msg><![CDATA[OK]]></return_msg>"+"</xml>";
            	}
            }else{
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
                logger.info("支付失败:"+resXml);
            }
        }else{
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
            logger.info("【订单支付失败】");
        }
        
        logger.info("【小程序支付回调响应】 响应内容：\n"+resXml);
        response.getWriter().print(resXml);
	}

}